package com.icinfo.cloud.provider.punish.common.datareport.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.exception.DataReportException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.SpringContextUtil;
import com.icinfo.cloud.provider.punish.approval.dto.ApprovalOpinionQueryDto;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.vo.CaseApprovalCompleteRecordVo;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseDataReportRecordQueryDto;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseDataReportRequestCommonDto;
import com.icinfo.cloud.provider.punish.common.datareport.dto.RevokeDecisionOrCaseInfoDto;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CaseDataReportOptTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.enums.ReportDataTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.enums.ReportRevokeTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.mapper.CaseDataReportRecordMapper;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataReportRecord;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportRecordService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportStageInfoService;
import com.icinfo.cloud.provider.punish.common.datareport.vo.CaseDataReportRecordVo;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.DocumentSendRecordQueryDto;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.DocumentSendStatusEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.service.IDocumentSendRecordService;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.DocumentSendRecordVo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseMainDetailAuxiliaryInfoRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CasePartiesRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailAuxiliaryInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailSimpleInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.InformHtmlRequest;
import com.icinfo.cloud.provider.punish.ucase.punishinform.service.ICaseCollectiveDiscussService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.CaseCollectiveDiscussVo;
import com.icinfo.framework.common.web.Result;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：案件数据上报接口实现类-处罚决定信息
 *
 * @author xiangyuyu
 * @date 2022/6/13 20:04
 */
@Slf4j
@Service
public class CaseDataReportDecisionServiceImpl implements ICaseDataReportService {
    private static final String TERRITORY_CODE_PREFIX = "001";
    /**
     * 行政处罚决定推送接口
     */
    private static final String DECISION_HTTP = "2Yt9eL497ZdbM0bf.htm";
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private IDocumentSendRecordService documentSendRecordService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;
    @Resource
    private ICaseCollectiveDiscussService caseCollectiveDiscussService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseDataReportStageInfoService caseDataReportStageInfoService;
    @Resource
    private ICaseDataReportRecordService caseDataReportRecordService;
    @Resource
    private CaseDataReportBasicServiceImpl basicService;
    @Resource
    private CaseDataReportInvestigateServiceImpl investigateService;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService ;
    @Resource
    private CaseDataReportRecordMapper caseDataReportRecordMapper;

    /**
     * 描述：收集数据上报-决定信息
     *
     * @param caseMainInfoVo   {@link CaseMainInfoVo}
     * @param reportDataType   上报数据类型
     * @param isUpdateReReport 是否更新补推
     * @param partyInfo        {@link CasePartiesInfoVo} 当事人信息
     * @param optType          更新类型
     * @return {@link JSONObject} 上报数据内容
     * @author xiangyuyu
     * @date 2022-03-31 23:18
     */
    @SneakyThrows
    @Override
    public JSONObject reportDataCollect(CaseMainInfoVo caseMainInfoVo, String reportDataType, boolean isUpdateReReport, CasePartiesInfoVo partyInfo, String optType) {
        JSONObject returnInfo = new JSONObject();
        log.info("collectReportCaseDecisionInfo start...param-caseMainInfo:{},reportDataType:{}", caseMainInfoVo, reportDataType);
        JSONObject decisionInfo = new JSONObject();
        String caseId = caseMainInfoVo.getId();
        String caseTerritoryCode = caseMainInfoVo.getCaseTerritoryCode();
        String sourceDeptCode = TERRITORY_CODE_PREFIX + caseTerritoryCode;
        String partyId = partyInfo.getPartyId();
        CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
        queryDto.setCaseId(caseId);
        queryDto.setReportDataType(reportDataType);
        queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
        queryDto.setPartyId(partyId);
        //默认测试数据1
        String envFlag = Constant.STRING_1;
        if (SpringContextUtil.checkIsPrdProfile()) {
            queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
            envFlag = Constant.STRING_0;

        }
        List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
        String reportActionType = "I";
        if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
            CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
            String latestReportResult = latestRecord.getReportResult();
            if (!Constant.STRING_0.equals(latestReportResult)) {
                String oriActionType = latestRecord.getReportActionType();
                reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
            } else {
                reportActionType = "U";
            }
        }
        if (isUpdateReReport) {
            reportActionType = "U";
        }
        String caseType = caseMainInfoVo.getCaseType();
        CaseMainDetailInfo caseMainDetailInfo;
        CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = null;
        if(CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)){
            //简易处罚
            caseMainDetailInfo = new CaseMainDetailInfo();
            caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            if(ObjectUtils.isEmpty(caseMainDetailSimpleInfo)){
                throw new BusinessException("未匹配到简易处罚的案件详情信息-caseId:"+caseId);
            }
            caseMainDetailInfo.setIsImportantCase(YesOrNoEnum.NO.getCode());
        } else {
            //TODO：目前暂时将简易处罚之外的案件的宽表数据认为存储在case_main_detail_info,后期如果有新增宽表，得特殊处理
            caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
        }

        String isImportantCase = caseMainDetailInfo.getIsImportantCase();

        decisionInfo.put("recordUniqueIdentity", BaseUtil.createUid());
        /*
            如果当事人id为空，则说明是单当事人/多当事人合并处罚，
            则caseId作为 punishBaseInfoCode，
            否则取当事人id作为 punishBaseInfoCode
         */
        String uid = partyId;
        //是否是多当事人分别处罚
        boolean isMultiplePartiesAndPartPunish = !ObjectUtils.isEmpty(partyId)?true:false;
        if(!isMultiplePartiesAndPartPunish){
            uid = caseId;
        }
        decisionInfo.put("punishBaseInfoCode", uid);

        String illegalFact;
        String punishKind;
        //没收违法所得
        String confiscateIllegalMoney = null;
        //没收非法财务价值
        String confiscateIllegalPropertyValue = null;
        //拟处罚金额
        String draftPunishMoney = null;
        String isPublicity;
        String publicText = null;
        String punishContent = null;

        String punishDocumentCode;
        String investConclusion;
        String otherContent;
        if(isMultiplePartiesAndPartPunish){
            //获取案件详情补充表信息
            CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest(caseId,partyId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryList = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
            if(!ObjectUtils.isEmpty(caseMainDetailAuxiliaryList) && caseMainDetailAuxiliaryList.size() > 0){
                CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryList.get(Constant.INTEGER_0);
                illegalFact = caseMainDetailAuxiliaryInfo.getIllegalFact();
                punishKind = caseMainDetailAuxiliaryInfo.getPunishKinds();
                punishContent = caseMainDetailAuxiliaryInfo.getPunishContent();
                confiscateIllegalMoney = caseMainDetailAuxiliaryInfo.getConfiscateIllegalMoney();
                draftPunishMoney = caseMainDetailAuxiliaryInfo.getDraftPunishMoney();
                isPublicity =  caseMainDetailAuxiliaryInfo.getIsPublicity();
                publicText = caseMainDetailAuxiliaryInfo.getPublicityContent();
                punishDocumentCode = caseMainDetailAuxiliaryInfo.getPunishDocumentNumber();
                investConclusion = caseMainDetailAuxiliaryInfo.getInvestConclusion();
                otherContent = caseMainDetailAuxiliaryInfo.getOtherContent();
                confiscateIllegalPropertyValue = caseMainDetailAuxiliaryInfo.getConfiscateIllegalPropertyValue();
            } else {
                illegalFact = Constant.STRING_HORIZONTAL_BARS;
                punishKind = Constant.STRING_HORIZONTAL_BARS;
                punishDocumentCode = Constant.STRING_HORIZONTAL_BARS;
                investConclusion = Constant.STRING_HORIZONTAL_BARS;
                isPublicity = Constant.STRING_0;
                otherContent = "-";
            }
            if(ObjectUtils.isEmpty(illegalFact) || Constant.STRING_HORIZONTAL_BARS.equals(illegalFact)){
                illegalFact = caseMainDetailInfo.getIllegalFact();
            }

        } else {
            illegalFact = caseMainDetailInfo.getIllegalFact();
            punishKind = caseMainDetailInfo.getPunishKinds();
            punishContent = caseMainDetailInfo.getPunishContent();
            confiscateIllegalMoney = caseMainDetailInfo.getConfiscateIllegalMoney();
            confiscateIllegalPropertyValue = caseMainDetailInfo.getConfiscateIllegalPropertyValue();
            draftPunishMoney = caseMainDetailInfo.getDraftPunishMoney();
            isPublicity =  caseMainDetailInfo.getIsPublicity();
            publicText = caseMainDetailInfo.getPublicityContent();
            punishDocumentCode = caseMainDetailInfo.getPunishDocumentNumber();
            investConclusion = caseMainDetailInfo.getInvestConclusion();
            otherContent = caseMainDetailInfo.getOtherContent();
        }

        //是否集体议案（数据上报规则：0-否/1-是）
        String isGroupDiscuss = caseMainDetailInfo.getIsNeedCollectiveDiscuss();
        LocalDateTime caseHappenTime = caseMainDetailInfo.getCaseHappenTime();
        String caseHappenAddressDetail = caseMainDetailInfo.getCaseHappenAddressDetailFull();

        if(CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)){
            illegalFact = caseMainDetailSimpleInfo.getIllegalFact();
            punishKind = caseMainDetailSimpleInfo.getPunishKinds();
            draftPunishMoney = caseMainDetailSimpleInfo.getDraftPunishMoney();
            //confiscateIllegalMoney = caseMainDetailSimpleInfo.getDraftPunishMoney();
            //20220927 简易处罚案件不公示
            isPublicity =  YesOrNoEnum.NO.getCode();

            String punishDesc;
            //简易程序的展示处罚种类，若罚款的展示罚款金额。
            if ("罚款".equals(punishKind)) {
                punishDesc = "罚款" + draftPunishMoney + "元";
            } else if (punishKind.contains("罚款") && punishKind.contains("警告")) {
                punishDesc = "警告并罚款" + draftPunishMoney + "元";
            } else {
                punishDesc = caseMainDetailSimpleInfo.getPunishKinds();
            }
            punishContent = punishDesc;
            publicText = "";
            isGroupDiscuss = YesOrNoEnum.NO.getCode();
            punishDocumentCode = caseMainDetailSimpleInfo.getPunishDocumentNumber();
            investConclusion = "";
        }
        decisionInfo.put("isMajorCase", ObjectUtils.isEmpty(isImportantCase)?YesOrNoEnum.NO.getCode():isImportantCase);
        //判断是否法制审核（上报数据规则：0-否/1-是）
        //处罚决定书目录编码：CFJDS0F62A(审批表：CFJDSPBFC20F)
        String kindCode = Constant.STRING_KIND_CODE_CFJDSPB;
        if(!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfoVo.getCaseType()) && Constant.STRING_2.equals(investConclusion)){
            kindCode = Constant.STRING_KIND_CODE_BYCFJDSPB;
        }
        List<ConfigBusiParamDocumentInfo> configDocList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId,caseMainInfoVo,kindCode);
        String documentCatalogCode;
        if(!ObjectUtils.isEmpty(configDocList)){
            documentCatalogCode = configDocList.get(Constant.INTEGER_0).getDocumentCatalogCode();
        } else {
            throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
        }
        ConfigBusiParamDocumentInfo configInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtils.isEmpty(configInfo)) {
            throw new DataReportException("未找到文书配置信息-collectReportCaseDecisionInfo documentCatalogCode:" + documentCatalogCode);
        }
        String approveId = configInfo.getApproveId();
        //查询是否需要法制审核、法制审核审批信息
        ApprovalOpinionQueryDto opinionQueryDto = new ApprovalOpinionQueryDto();
        opinionQueryDto.setCaseId(caseId);
        opinionQueryDto.setApprovalOpinionType(Constant.STRING_2);
        opinionQueryDto.setApprovalStatus("agree");
        opinionQueryDto.setDocumentCatalogCode(documentCatalogCode);
        List<CaseApprovalCompleteRecordVo> approvalCompleteRecordList = caseApprovalCompleteRecordMapper.selectCheckOpinionInfo(opinionQueryDto);
        String isLegalReview = YesOrNoEnum.NO.getCode();
        if (!ObjectUtils.isEmpty(approvalCompleteRecordList) || approvalCompleteRecordList.size() > 0) {
            isLegalReview = YesOrNoEnum.YES.getCode();
            CaseApprovalCompleteRecordVo latestRecord = approvalCompleteRecordList.get(Constant.INTEGER_0);
            //法制审核日期
            decisionInfo.put("legalReviewDate", latestRecord.getApprovalTime());
            //法制审核意见
            decisionInfo.put("legalReviewOpinions", ObjectUtils.isEmpty(latestRecord.getApprovalOpinion()) ? "无意见" : latestRecord.getApprovalOpinion());
        }
        decisionInfo.put("isLegalReview", isLegalReview);


        decisionInfo.put("isGroupDiscuss", isGroupDiscuss);
        if (YesOrNoEnum.YES.getCode().equals(isGroupDiscuss)) {
            //获取集体议案信息
            InformHtmlRequest requestInfo = new InformHtmlRequest();
            requestInfo.setCaseId(caseId);
            CaseCollectiveDiscussVo vo = caseCollectiveDiscussService.getCaseCollectiveDiscussBaseInfo(requestInfo);
            //TODO：应数浙要求，该字段数据上报格式取消下划线，线上验证通过后，取消该注释 20221129
            decisionInfo.put("groupDiscussionDate", vo.getDiscussDate());
            if(StrUtil.isNotEmpty(vo.getPubishSuggestion())){
                decisionInfo.put("groupDiscussionConclusion", vo.getPubishSuggestion());
            }else {
                decisionInfo.put("groupDiscussionConclusion", vo.getPunishContent());
            }
        }
        decisionInfo.put("illegalFact", illegalFact);
        CaseReasonMainRecordVo caseReasonMainRecord = caseReasonMainRecordService.getCaseReasonRecordByCaseId(caseId);
        if (ObjectUtils.isEmpty(caseReasonMainRecord)) {
            throw new DataReportException("collectReportCaseDecisionInfo 未找到案件案由记录信息,caseId:" + caseId);
        } else {
            decisionInfo.put("illegalBasis", caseReasonMainRecord.getIllegalBasis());
            decisionInfo.put("punishBasis", caseReasonMainRecord.getPunishBasis());
        }
        String decisionType = "01";
        if (Constant.STRING_2.equals(investConclusion)) {
            //不予处罚
            decisionType = "02";
        }

        decisionInfo.put("decisionType", decisionType);

        String punishType = "";
        Map<String, String> punishTypeMap = new HashMap<>(16);
        punishTypeMap.put("警告", "01");
        punishTypeMap.put("罚款", "02");
        punishTypeMap.put("没收违法所得", "03");
        punishTypeMap.put("没收非法财物", "03");
        punishTypeMap.put("责令停产停业", "04");
        punishTypeMap.put("暂扣或者吊销许可证、暂扣或者吊销执照", "05");
        punishTypeMap.put("吊销许可证", "05");
        punishTypeMap.put("行政拘留", "06");
        punishTypeMap.put("其他", "07");
        if (!ObjectUtils.isEmpty(punishKind)) {
            String[] punishKindArr = punishKind.split(",");
            for (String s : punishKindArr) {
                String value = punishTypeMap.get(s);
                if (ObjectUtils.isEmpty(value)) {
                    punishType += "07^";
                } else {
                    punishType += value + "^";
                }

            }
        } else {
            //默认为07【正常业务逻辑不可能出现为空】
            punishType = "07";
        }
        if (punishType.endsWith("^")) {
            punishType = punishType.substring(0, punishType.length() - 1);
        }
        decisionInfo.put("punishType", punishType);
        decisionInfo.put("punishContent", ObjectUtils.isEmpty(punishContent)? Constant.STRING_HORIZONTAL_BARS:punishContent);
        //罚款金额
        String fine = "0.00";
        String confiscateIllegalIncom = "0.00";
        String confiscateIllegalAsset = "0.00";

        double confiscateIllegalMoneyD = 0D;
        double draftPunishMoneyD = 0D;
        double confiscateIllegalPropertyValueD = 0D;
        if (!ObjectUtils.isEmpty(confiscateIllegalMoney)) {
            confiscateIllegalMoneyD = Double.parseDouble(confiscateIllegalMoney);
        }
        if (!ObjectUtils.isEmpty(draftPunishMoney)) {
            draftPunishMoneyD = Double.parseDouble(draftPunishMoney);
        }
        if(StrUtil.isNotEmpty(confiscateIllegalPropertyValue)){
            confiscateIllegalPropertyValueD = Double.parseDouble(confiscateIllegalPropertyValue);
        }
        //罚款金额总计
        /*double totalPunishMoney = confiscateIllegalMoneyD + draftPunishMoneyD;
        if (totalPunishMoney > 0) {
            fine = String.valueOf(totalPunishMoney);
            confiscateIllegalIncom = fine;
        }*/
        //罚款
        if(draftPunishMoneyD > 0){
            fine = String.valueOf(draftPunishMoneyD);
        }
        //没收违法金额
        if(confiscateIllegalMoneyD > 0){
            confiscateIllegalIncom = String.valueOf(confiscateIllegalMoneyD);
        }
        //没收非法财务
        if(confiscateIllegalPropertyValueD > 0){
            confiscateIllegalAsset = String.valueOf(confiscateIllegalPropertyValueD);
        }
        decisionInfo.put("fine", fine);
        decisionInfo.put("confiscateIllegalIncom", confiscateIllegalIncom);
        decisionInfo.put("confiscateIllegalAsset", confiscateIllegalAsset);

        if (punishType.contains("06")) {
            decisionInfo.put("detainDays", "-");
            decisionInfo.put("detainStartDate", "-");
            decisionInfo.put("detainEndDate", "-");
        } else {
            decisionInfo.put("detainDays", "0");
            decisionInfo.put("detainStartDate", null);
            decisionInfo.put("detainEndDate", null);
        }
        if (punishTypeMap.containsKey("其他")) {
            decisionInfo.put("otherContent", ObjectUtils.isEmpty(otherContent)?"-":otherContent);
        } else {
            decisionInfo.put("otherContent", "");
        }

        //decisionInfo.put("setTime", caseMainInfoVo.getCaseVerdictEndTime());
        //获取处罚决定相关信息（处罚决定书目录编码：CFJDS0F62A）
        String tmpKindCode = Constant.STRING_KIND_CODE_CFJDS;
        //简易处罚
        if(CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfoVo.getCaseType())){
            tmpKindCode = Constant.STRING_KIND_CODE_JYCXCFJDS;
        }
        //如果是行政处理的话
        if(Constant.STRING_2.equals(caseMainDetailInfo.getHandleConclusion())){
            tmpKindCode = Constant.STRING_KIND_CODE_CLJDS;
        }
        if(!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfoVo.getCaseType()) && Constant.STRING_2.equals(investConclusion)){
            tmpKindCode = Constant.STRING_KIND_CODE_BYCFJDS;
        }
        List<ConfigBusiParamDocumentInfo> tmpConfigDocList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId,caseMainInfoVo,tmpKindCode);
        String documentCatalogCodeCfjds;
        if(!ObjectUtils.isEmpty(tmpConfigDocList)){
            documentCatalogCodeCfjds = tmpConfigDocList.get(Constant.INTEGER_0).getDocumentCatalogCode();
        } else {
            throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",tmpKindCode:" + tmpKindCode);
        }

        CaseDocumentRecordQueryDto query = new CaseDocumentRecordQueryDto();
        query.setCaseId(caseId);
        query.setDocumentKindCode(tmpKindCode);
        //如果是多当事人分别处罚，则加入partyId参数
        if(isMultiplePartiesAndPartPunish){
            query.setPartyId(partyId);
        }
        query.setRevokeType(caseMainInfoVo.getRevokeType());
        List<CaseDocumentRecordVo> caseDocumentRecordList = caseDocumentRecordService.getCaseDocumentRecordList(query);
        CaseDocumentRecordVo caseDocumentRecordCfjds;
        if(ObjectUtils.isEmpty(caseDocumentRecordList) || caseDocumentRecordList.size() == 0){
            throw new DataReportException("collectReportCaseDecisionInfo 未找文书记录信息 caseId,documentCatalogCodeCfjds:" + caseId + "," + documentCatalogCodeCfjds);
        } else {
            caseDocumentRecordCfjds = caseDocumentRecordList.get(Constant.INTEGER_0);
        }
        //决定书文号
        decisionInfo.put("punishDocumentCode", punishDocumentCode);
        //决定理由
        //decisionInfo.put("punishReson", "");
        //决定书 互联网地址
        decisionInfo.put("punishDocument", caseDocumentRecordCfjds.getDocumentUrlAfterSeal());
        //多当事人时，决定日期从文书记录表里取值
        decisionInfo.put("setTime", caseDocumentRecordCfjds.getDocumentApprovalTime() == null ? caseDocumentRecordCfjds.getDocumentCreateTime() : caseDocumentRecordCfjds.getDocumentApprovalTime());
        LocalDateTime sentTime = caseDocumentRecordCfjds.getSentTime();
        //简易处罚送达时间用结案时间
        if(CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)){
            sentTime = caseMainInfoVo.getCaseEndTime();
        }
        decisionInfo.put("deliverDate", sentTime);

        DocumentSendRecordQueryDto q = new DocumentSendRecordQueryDto();
        q.setCaseId(caseId);
        q.setDocumentId(caseDocumentRecordCfjds.getId());
        q.setSendStatus(DocumentSendStatusEnum.SEND_SUCCESS.getCode());
        List<DocumentSendRecordVo> documentSendRecordList = documentSendRecordService.getDocumentSendRecordList(q);
        //默认电子送达
        String deliverMode = "06";
        if (!ObjectUtils.isEmpty(documentSendRecordList) && documentSendRecordList.size() > 0) {
            DocumentSendRecordVo sendRecord = documentSendRecordList.get(Constant.INTEGER_0);
            Map<String, String> sentWayMap = new HashMap<>(8);
            sentWayMap.put("直接送达", "01");
            sentWayMap.put("留置送达", "02");
            sentWayMap.put("委托送达", "03");
            sentWayMap.put("邮递送达", "04");
            sentWayMap.put("公告送达", "05");
            sentWayMap.put("其他方式送达", "99");
            sentWayMap.put("电子送达", "06");
            //默认电子送达
            deliverMode = ObjectUtils.isEmpty(sentWayMap.get(sendRecord.getSentWayName())) ? deliverMode : sentWayMap.get(sendRecord.getSentWayName());
        }
        decisionInfo.put("deliverMode", deliverMode);

        String isPublic = Constant.STRING_1;
        if (Constant.STRING_0.equals(isPublicity)) {
            isPublic = Constant.STRING_0;
        }
        //20220927 简易处罚案件不公示
        decisionInfo.put("isPublic", isPublic);
        //decisionInfo.put("ppSentDate", jgCase.getExtraInfo().getXzcfjd());
        //20220726-公示时间由系统当前时间改成送达时间
        if (!ObjectUtils.isEmpty(sentTime)) {
            decisionInfo.put("publicDate", sentTime);
        } else {
            //超过10个工作日未送达改造
            decisionInfo.put("publicDate", LocalDateTime.now());
        }
        if (punishType.contains("05")) {
            decisionInfo.put("isRevoked", YesOrNoEnum.YES.getCode());
            decisionInfo.put("revokeLicenceName", "-");
            decisionInfo.put("revokeLicenceCode", "-");
            // FIXME: 2022/11/30 暂时用送达时间来代替，目前没有这块业务
            decisionInfo.put("detainCertStartDate", sentTime);
            decisionInfo.put("detainCertEndDate", sentTime);
        } else {
            decisionInfo.put("isRevoked", "0");
        }
        if (ObjectUtils.isEmpty(publicText)) {
            //兜底方案
            StringBuilder tmpTxt = new StringBuilder();
            CasePartiesDetailInfoVo vo = casePartiesRecordService.getCasePartiesDetailInfo(caseId);
            if (ObjectUtils.isEmpty(vo)) {
                throw new DataReportException("未找到当事人信息 caseId:" + caseId);
            }
            String partyName;
            if (PartyTypeEnum.PERSON.getCode().equals(vo.getPartyType())) {
                partyName = vo.getCasePartiesPersonInfo().getName();
            } else {
                partyName = vo.getCasePartiesLegalInfo().getEntName();
            }
            tmpTxt.append(partyName);
            tmpTxt.append("于");


            if (!ObjectUtils.isEmpty(caseHappenTime)) {
                String time = caseHappenTime.toLocalDate().toString();
                tmpTxt.append(time);
            } else {
                tmpTxt.append(" ");
            }
            tmpTxt.append("在");
            if (ObjectUtils.isEmpty(caseHappenAddressDetail)) {
                caseHappenAddressDetail = caseMainDetailInfo.getCaseHappenAddressDetail();
            }
            if (ObjectUtils.isEmpty(caseHappenAddressDetail)) {
                caseHappenAddressDetail = " ";
            }
            tmpTxt.append(caseHappenAddressDetail);
            tmpTxt.append("实施了");
            tmpTxt.append(caseReasonMainRecord.getCaseReasonNameSimple());
            tmpTxt.append("的行为，违反了");
            tmpTxt.append(caseReasonMainRecord.getIllegalBasisFormat());
            tmpTxt.append("，依据");
            tmpTxt.append(caseReasonMainRecord.getPunishBasisFormat());
            tmpTxt.append(",作出如下行政处罚：");
            String casePunishContent = ObjectUtils.isEmpty(punishContent) ? "-" : punishContent;
            tmpTxt.append(casePunishContent);
            publicText = tmpTxt.toString();
        }
        decisionInfo.put("publicText", publicText);
        //公示状态（正常、撤销、删除）-0:正常，1：撤销，2：删除
        decisionInfo.put("publicStatus", "0");
        decisionInfo.put("optType", !ObjectUtils.isEmpty(optType) ? optType :reportActionType);
        decisionInfo.put("envFlag", envFlag);
        decisionInfo.put("sourceDeptCode", sourceDeptCode);
        returnInfo.put("decisionInfo", decisionInfo);
        //到dataReport时清空该键值
        returnInfo.put("reportActionType",!ObjectUtils.isEmpty(optType)?optType:reportActionType);
        returnInfo.put("envFlag", envFlag);
        log.info("collectReportCaseDecisionInfo end...result-returnInfo", returnInfo);
        return returnInfo;
    }


    /**
     * 描述：数据上报-decision
     *
     * @param dto          {@link CaseDataReportRequestCommonDto}
     * @param partyInfo    {@link CasePartiesInfoVo} 当事人信息
     * @param caseMainInfo {@link CaseMainInfoVo} 案件主体信息
     * @return {@link Result<String>} 上报结果
     * @author xiangyuyu
     * @date 2022-03-30 21:23
     */
    @Override
    public Result<String> singleCaseReport(CaseDataReportRequestCommonDto dto, CasePartiesInfoVo partyInfo, CaseMainInfoVo caseMainInfo) {
        log.info("dataReportDecision start... dto:{}", dto);
        String caseId = dto.getCaseId();
        String optType = dto.getOptType();
        if(!ObjectUtils.isEmpty(optType)){
            if(!CaseDataReportOptTypeEnum.isLegalEnumCode(optType)){
                throw new BusinessException("请指定有效的数据上报更新类型枚举(I：新增， U：修改； D：删除)");
            }
        }
        if (!caseDataReportRecordService.personalCheckIsAllowDataReport(caseId, null)) {
            log.info("该案件暂不开启数据上报-caseId:{}", caseId);
            return Result.error("该案件暂不开启数据上报-caseId:" + caseId);
        }
        List<CasePartiesInfoVo> partiesInfo = new ArrayList<>();
        if (ObjectUtils.isEmpty(partyInfo)) {
            //获取当事人信息
            if (ObjectUtils.isEmpty(caseMainInfo)) {
                caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
            }
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            String handleType = caseMainInfo.getHandleType();
            CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto(caseId, null, YesOrNoEnum.NO.getCode());
            partiesInfo = casePartiesRecordService.getCasePartiesInfoList(queryDto);
            if (!(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                    && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType))
            ) {
                //只取第一个当事人信息
                List<CasePartiesInfoVo> tmp = new ArrayList<>();
                tmp.add(partiesInfo.get(Constant.INTEGER_0));
                partiesInfo = tmp;
                partiesInfo.forEach(p -> p.setPartyId(null));
            }
        } else {
            partiesInfo.add(partyInfo);
        }
        for (CasePartiesInfoVo p : partiesInfo) {
            String partyId = p.getPartyId();
            try {
                if (caseDataReportRecordService.getIsAllowDataReport(caseId)) {
                    String errorMsg = "";
                    //根据案件id查询案件信息
                    CaseMainInfoVo vo = caseMainInfoService.getCaseMainInfo(caseId);
                    String uri = DECISION_HTTP;
                    String reportDataType = ReportDataTypeEnum.DECISION.getCode();
                    JSONObject tmpData = reportDataCollect(vo, reportDataType, false,p, optType);
                    JSONObject reportData = new JSONObject(8);
                    reportData.put("reportActionType", !ObjectUtils.isEmpty(optType)?optType:tmpData.get("reportActionType"));
                    reportData.put("envFlag", tmpData.get("envFlag"));
                    tmpData.remove("envFlag");
                    tmpData.remove("reportActionType");
                    reportData.put("decisionInfo", tmpData);
                    Map<String, String> params = new HashMap<>(20);
                    for (Map.Entry<String, Object> e : reportData.entrySet()) {
                        params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
                    }
                    errorMsg = caseDataReportRecordService.dataReport(uri, reportDataType, params, vo);
                    log.info("dataReportDecision end");
                    if (ObjectUtils.isEmpty(errorMsg)) {
                        caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.DECISION.getCode(), null,partyId);
                        //上报成功更新公示时间
                        updatePublicDateAndUrl(caseId, tmpData);
                    } else {
                        if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
                            caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.DECISION.getCode(), errorMsg,partyId);
                            //上报成功更新公示时间
                            updatePublicDateAndUrl(caseId, tmpData);
                        } else if(errorMsg.contains(Constant.STRING_ERROR_SIGN)) {
                            caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, reportDataType);
                        } else {
                            caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.DECISION.getCode(), errorMsg,partyId);
                        }
                        return Result.error(errorMsg);
                    }
                } else {
                    String tmpMsg = "该部门是否允许上报数据按钮处于关闭状态,caseId:" + caseId;
                    throw new BusinessException(tmpMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.DECISION.getCode(), e.getMessage(),partyId);
                return Result.error("dataReportDecision catch exception：" + e.getMessage());
            }

        }
        return Result.success("上报成功");
    }

    /**
     * 描述：数据上报-decision-撤销公示/撤销案件
     *
     * @param dto {@link RevokeDecisionOrCaseInfoDto}
     * @return {@link Result<String>} 上报结果
     * @author xiangyuyu
     * @date 2022/7/28
     */
    private Result<String> singleCaseReportRevoke(RevokeDecisionOrCaseInfoDto dto) {
        log.info("dataReportDecision start... dto:{}", dto);
        CasePartiesInfoVo partyInfo = null;
        CaseMainInfoVo caseMainInfo = null;
        String caseIdTmp = dto.getCaseId();
        List<String> caseIdList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(caseIdTmp)) {
            caseIdList.add(caseIdTmp);
        } else {
            caseIdList = dto.getCaseIdList();
        }

        StringBuilder errorMsgTotal = new StringBuilder();
        if (caseIdList.size() > 0) {
            for (String caseId : caseIdList) {
                List<CasePartiesInfoVo> partiesInfo;
                caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
                String handleType = caseMainInfo.getHandleType();
                CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto(caseId, null, YesOrNoEnum.NO.getCode());
                partiesInfo = casePartiesRecordService.getCasePartiesInfoList(queryDto);
                if (!(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                        && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType))
                ) {
                    //只取第一个当事人信息
                    List<CasePartiesInfoVo> tmp = new ArrayList<>();
                    tmp.add(partiesInfo.get(Constant.INTEGER_0));
                    partiesInfo = tmp;
                    partiesInfo.forEach(p -> p.setPartyId(null));
                } else {
                    String partyIdInput = dto.getPartyId();
                    if (ObjectUtils.isEmpty(partyIdInput)) {
                        return Result.error("未指定当事人id");
                    } else {
                        boolean isLegalPartyId = false;
                        for (CasePartiesInfoVo casePartiesInfoVo : partiesInfo) {
                            if (casePartiesInfoVo.getPartyId().equals(partyIdInput)) {
                                isLegalPartyId = true;
                                break;
                            }
                        }
                        if (!isLegalPartyId) {
                            return Result.error("非法当事人id");
                        }
                    }
                }
                for (CasePartiesInfoVo p : partiesInfo) {
                    String partyId = p.getPartyId();
                    try {
                        if (caseDataReportRecordService.getIsAllowDataReport(caseId)) {
                            String errorMsg = "";
                            //根据案件id查询案件信息
                            CaseMainInfoVo vo = caseMainInfoService.getCaseMainInfo(caseId);
                            String uri = DECISION_HTTP;
                            String reportDataType = ReportDataTypeEnum.DECISION.getCode();
                            vo.setRevokeType(dto.getRevokeType());
                            JSONObject tmpData = reportDataCollect(vo, reportDataType, false, p,null);
                            log.info("before deal revoke tmpData:{}", tmpData.toJSONString());
                            JSONObject decisionInfo = (JSONObject) tmpData.get("decisionInfo");
                            log.info("before deal revoke decision info :{}", decisionInfo.toJSONString());
                            String revokeType = dto.getRevokeType();
                            //撤销公示
                            decisionInfo.put("isPublic", Constant.STRING_1);
                            decisionInfo.put("publicStatus", Constant.STRING_1);
                            decisionInfo.put("cutReason", dto.getRevokeReason());
                            if (ReportRevokeTypeEnum.REVOKE_CASE.getCode().equals(revokeType)) {
                                //撤案
                                decisionInfo.put("publicStatus", Constant.STRING_1);
                                decisionInfo.put("punishDecisionStatus", Constant.STRING_1);
                                List<ConfigBusiParamDocumentInfo> tmpConfigDocList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId,vo,Constant.STRING_KIND_CODE_XZCFCXJDS);
                                String documentCatalogCodeCxcfjds;
                                CaseDocumentRecordVo caseDocumentRecordCxcfjds;
                                if(!ObjectUtils.isEmpty(tmpConfigDocList)){
                                    documentCatalogCodeCxcfjds = tmpConfigDocList.get(Constant.INTEGER_0).getDocumentCatalogCode();
                                } else {
                                    throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",tmpKindCode:" + Constant.STRING_KIND_CODE_XZCFCXJDS);
                                }

                                CaseDocumentRecordQueryDto query = new CaseDocumentRecordQueryDto();
                                query.setCaseId(caseId);
                                query.setDocumentKindCode(Constant.STRING_KIND_CODE_XZCFCXJDS);
                                List<CaseDocumentRecordVo> caseDocumentRecordList = caseDocumentRecordService.getCaseDocumentCxRecordList(query);
                                if(ObjectUtils.isEmpty(caseDocumentRecordList) || caseDocumentRecordList.size() == 0){
                                    throw new DataReportException("collectReportCaseDecisionInfo 未找文书记录信息 caseId,documentCatalogCodeCfjds:" + caseId + "," + documentCatalogCodeCxcfjds);
                                } else {
                                    caseDocumentRecordCxcfjds = caseDocumentRecordList.get(Constant.INTEGER_0);
                                }
                                decisionInfo.put("punishDecisionCancelDocUrl", caseDocumentRecordCxcfjds.getDocumentUrlAfterSeal());
                            }
                            log.info("after deal revoke decision info :{}", decisionInfo);
                            tmpData.put("decisionInfo", decisionInfo);
                            log.info("after deal revoke tmpData:{}", tmpData.toJSONString());
                            JSONObject reportData = new JSONObject(8);
                            reportData.put("reportActionType", tmpData.get("reportActionType"));
                            reportData.put("envFlag", tmpData.get("envFlag"));
                            tmpData.remove("envFlag");
                            tmpData.remove("reportActionType");
                            reportData.put("decisionInfo", tmpData);
                            Map<String, String> params = new HashMap<>(20);
                            for (Map.Entry<String, Object> e : reportData.entrySet()) {
                                params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
                            }
                            errorMsg = caseDataReportRecordService.dataReport(uri, reportDataType, params, vo);
                            log.info("dataReportDecision end");
                            if (ObjectUtils.isEmpty(errorMsg)) {
                                caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.DECISION.getCode(), null, partyId);
                                continue;
                            } else {
                                if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
                                    caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.DECISION.getCode(), errorMsg, partyId);
                                } else {
                                    caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.DECISION.getCode(), errorMsg, partyId);
                                }
                                errorMsgTotal.append(errorMsg);
                            }
                        } else {
                            String tmpMsg = "该部门是否允许上报数据按钮处于关闭状态,caseId:" + caseId;
                            errorMsgTotal.append(tmpMsg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.DECISION.getCode(), e.getMessage(), partyId);
                        return Result.error("dataReportDecision catch exception：" + e.getMessage());
                    }
                }
            }

        }
        String totalErrorMsg = errorMsgTotal.toString();
        if (!ObjectUtils.isEmpty(totalErrorMsg)) {
            return Result.error(totalErrorMsg);
        }
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 【V1.2.0】描述：处罚决定信息-撤销公示/撤案
     *
     * @param dto {@link RevokeDecisionOrCaseInfoDto}
     * @return Result<String> 上报结果
     * @author xiangyuyu
     * @date  2022/7/28
     */
    public Result<String> revokeDecisionOrCaseInfo(RevokeDecisionOrCaseInfoDto dto){
        if(ObjectUtils.isEmpty(dto.getCaseId()) && (ObjectUtils.isEmpty(dto.getCaseIdList()) || dto.getCaseIdList().size() == 0)){
            return Result.error("未指定案件id或案件id列表");
        }
        String revokeType = dto.getRevokeType();
        if(!ReportRevokeTypeEnum.isLegalEnumCode(revokeType)){
            return Result.error("非法撤销类型");
        }
        if(ObjectUtils.isEmpty(dto.getRevokeReason())){
            return Result.error("未指定撤销原因");
        }
        return singleCaseReportRevoke(dto);
    }
    /**
     * 【V2.0.0】描述：处罚决定信息-数据批量上报
     *
     * @param baseInfoReportFailCaseIdList 上报失败的案件id列表
     * @return 上报失败案件id列表
     * @author xiangyuyu
     * @date 2022-06-13 16:02
     */
    @Override
    public List<String> batchCaseReport(List<String> baseInfoReportFailCaseIdList) {
        if(ObjectUtils.isEmpty(baseInfoReportFailCaseIdList)){
            baseInfoReportFailCaseIdList = new ArrayList<>();
        }
        LocalDateTime startTime = LocalDateTime.now();
        log.info("basicInfoReport start-startTime:{}", startTime);
        //4、查看2天前是否存在"处罚决定书送达"的案件
        List<String> shouldUploadPunishDecideInfo = caseDocumentRecordService.getCaseIdListShouldReportDecideInfo();
        if (!ObjectUtils.isEmpty(shouldUploadPunishDecideInfo) && shouldUploadPunishDecideInfo.size() > 0) {
            //上报数据
            this.reportPunishDecideData(baseInfoReportFailCaseIdList, shouldUploadPunishDecideInfo);
        } else {
            log.info("date:{},无处罚决定书送达", startTime);
        }
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        long seconds = duration.getSeconds();
        log.info("basicInfoReport end-endTime:{},consume:{} s", endTime, seconds);
        return baseInfoReportFailCaseIdList;
    }

    /**
     * 【V2.0.0】描述：处罚决定信息-数据批量上报
     *
     * @param baseInfoReportFailCaseIdList 上报失败的案件id列表
     * @param punishDecideCaseIdList 已经查询出的处罚决定案件ID列表
     * @return 上报失败案件id列表
     * @author mahan
     * @date 2022-10-20 19:02
     */
    public List<String> batchCaseReport(List<String> baseInfoReportFailCaseIdList, List<String> punishDecideCaseIdList) {
        if(ObjectUtils.isEmpty(baseInfoReportFailCaseIdList)){
            baseInfoReportFailCaseIdList = new ArrayList<>();
        }
        LocalDateTime startTime = LocalDateTime.now();
        log.info("basicInfoReport start-startTime:{}", startTime);
        //4、查看2天前是否存在"处罚决定书送达"的案件
        //上报数据
        this.reportPunishDecideData(baseInfoReportFailCaseIdList, punishDecideCaseIdList);
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        long seconds = duration.getSeconds();
        log.info("basicInfoReport end-endTime:{},consume:{} s", endTime, seconds);
        return baseInfoReportFailCaseIdList;
    }

    /**
     * 上报数据
     * @param baseInfoReportFailCaseIdList
     * @param punishDecideCaseIdList
     */
    private void reportPunishDecideData(List<String> baseInfoReportFailCaseIdList, List<String> punishDecideCaseIdList) {
        log.info("处罚决定书送达数量:{}", punishDecideCaseIdList.size());
        List<String> finalBaseInfoReportFailCaseIdList = baseInfoReportFailCaseIdList;
        punishDecideCaseIdList.forEach(e -> {
            if (!finalBaseInfoReportFailCaseIdList.contains(e)) {
                CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(e);
                if(!caseDataReportRecordService.personalCheckIsAllowDataReport(e,caseMainInfo)){
                    return;
                }
                String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
                String handleType = caseMainInfo.getHandleType();
                CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto(e, null,YesOrNoEnum.NO.getCode());
                List<CasePartiesInfoVo> partiesInfo = casePartiesRecordService.getCasePartiesInfoList(queryDto);
                if (!(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                        && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType))
                ) {
                    //只取第一个当事人信息
                    List<CasePartiesInfoVo> tmp = new ArrayList<>();
                    tmp.add(partiesInfo.get(Constant.INTEGER_0));
                    partiesInfo = tmp;
                    partiesInfo.forEach(p -> p.setPartyId(null));
                }
                CaseDataReportRequestCommonDto dto = new CaseDataReportRequestCommonDto();
                dto.setCaseId(e);
                for (CasePartiesInfoVo partyInfo : partiesInfo) {
                    String partyId = partyInfo.getPartyId();
                    //校验是否需要上报
                    boolean isShouldReport = caseDataReportStageInfoService.checkIsShouldReport(ReportDataTypeEnum.DECISION.getCode(), e, partyId);
                    if (isShouldReport) {
                        //查看案件基础信息是否上报
                        if (!caseDataReportStageInfoService.checkStageInfoIsReportSuccess(ReportDataTypeEnum.BASE.getCode(), e, partyId)) {
                            Result<String> result = basicService.singleCaseReport(dto, partyInfo, caseMainInfo);
                            if (!caseDataReportRecordService.analyseResultToJudgeIsReportSuccess(result)) {
                                finalBaseInfoReportFailCaseIdList.add(e);
                            } else {
                                singleCaseReport(dto, partyInfo, caseMainInfo);
                            }
                        } else {
                            singleCaseReport(dto, partyInfo, caseMainInfo);
                        }
                        //多当事人的，查看对应调查取证信息是否数据上报
                        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                            //判断调查取证信息是否数据上报
                            if (!caseDataReportStageInfoService.checkStageInfoIsReportSuccess(ReportDataTypeEnum.INVESTIGATE.getCode(), e, null)) {
                                //不管处罚告知是分别处罚还是合并处罚，这里都合并一条数据上报即可
                                Result<String> result = investigateService.singleCaseReport(dto, partyInfo, caseMainInfo);
                                if (!caseDataReportRecordService.analyseResultToJudgeIsReportSuccess(result)) {
                                    finalBaseInfoReportFailCaseIdList.add(e);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * 描述：数据上报-decision（重推-U）
     *
     * @param caseId       案件id
     * @param partyInfo    {@link CasePartiesInfoVo} 当事人信息
     * @param caseMainInfo {@link CaseMainInfoVo} 案件主体信息
     * @return {@link Result<String>} 上报结果
     * @author xiangyuyu
     * @date 2022-04-22 16:27
     */
    @Override
    public Result<String> singleCaseReportAgain(String caseId, CasePartiesInfoVo partyInfo, CaseMainInfoVo caseMainInfo) {
        log.info("dataReportDecisionRe start... caseId:{}", caseId);
        if(ObjectUtils.isEmpty(partyInfo)){
            partyInfo = new CasePartiesInfoVo();
        }
        String partyId = partyInfo.getPartyId();
        try {
            if (caseDataReportRecordService.getIsAllowDataReport(caseId)) {
                String errorMsg = "";
                if(ObjectUtils.isEmpty(caseMainInfo)){
                    //根据案件id查询案件信息
                    caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                }
                String uri = DECISION_HTTP;
                String reportDataType = ReportDataTypeEnum.DECISION.getCode();
                JSONObject tmpData = reportDataCollect(caseMainInfo, reportDataType, true,partyInfo,CaseDataReportOptTypeEnum.U.getCode());
                JSONObject reportData = new JSONObject(8);
                reportData.put("reportActionType", tmpData.get("reportActionType"));
                reportData.put("envFlag", tmpData.get("envFlag"));
                tmpData.remove("envFlag");
                tmpData.remove("reportActionType");
                reportData.put("decisionInfo", tmpData);
                Map<String, String> params = new HashMap<>(20);
                for (Map.Entry<String, Object> e : reportData.entrySet()) {
                    params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
                }
                errorMsg = caseDataReportRecordService.dataReport(uri, reportDataType, params, caseMainInfo);
                log.info("dataReportDecisionRe end");
                if (ObjectUtils.isEmpty(errorMsg)) {
                    caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.DECISION.getCode(), null,partyId);
                    //上报成功更新公示时间
                    updatePublicDateAndUrl(caseId, tmpData);
                    return Result.success("上报成功");
                } else {
                    if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
                        caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.DECISION.getCode(), errorMsg,partyId);
                        //上报成功更新公示时间
                        updatePublicDateAndUrl(caseId, tmpData);
                    } else {
                        caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.DECISION.getCode(), errorMsg,partyId);
                    }
                    return Result.error(errorMsg);
                }
            } else {
                String tmpMsg = "该部门是否允许上报数据按钮处于关闭状态,caseId:" + caseId;
                throw new BusinessException(tmpMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.DECISION.getCode(), e.getMessage(),partyId);
            return Result.error("dataReportDecisionRe catch exception：" + e.getMessage());
        }
    }

    /**
     * 描述：批量案件重新数据上报（U）
     *
     * @return {@link Result <String>} 上报失败案件id列表
     * @author xiangyuyu
     * @date 2022-06-13 18:52
     */
    @Override
    public List<String> batchCaseReportAgain() {
        return null;
    }


    /**
     * 描述： 更新公示时间及地址
     *
     * @author: zhengqiang
     * @date: 2022/7/20
     * @param: caseId
     * @param: decisionObj
     * @return
     **/
    private void updatePublicDateAndUrl(String caseId, JSONObject decisionObj) {
        CaseDataReportRecord latestReportRecord = caseDataReportRecordService.getLatestReportRecord(caseId, ReportDataTypeEnum.DECISION.getCode());
        if (!ObjectUtils.isEmpty(latestReportRecord)) {
            //获取公示时间
            JSONObject decisionInfo = decisionObj.getJSONObject("decisionInfo");
            LocalDateTime publicDate = (LocalDateTime) decisionInfo.get("publicDate");
            latestReportRecord.setPublicDate(publicDate);
            //拼接url
            String punishDocumentCode = decisionInfo.getString("punishDocumentCode");
            String punishBaseInfoCode = decisionInfo.getString("punishBaseInfoCode");
            try {
                StringBuilder publicUrl = new StringBuilder("https://www.zjzwfw.gov.cn/zjservice/matter/punishment/detail.do?");
                publicUrl.append("unid=").append(URLEncoder.encode(punishDocumentCode, "UTF-8"));
                publicUrl.append("&webid=1");
                publicUrl.append("&guid=").append(punishBaseInfoCode);
                latestReportRecord.setPublicUrl(publicUrl.toString());
            } catch (Exception e) {
                log.error("公示地址拼接异常", e);
            }
            caseDataReportRecordMapper.updateByPrimaryKeySelective(latestReportRecord);
        }
    }
}
